package com.eascs.archive.service.impl;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.eascs.admin.common.vo.ModelResult;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.archive.dao.ArchiveAdminDao;
import com.eascs.archive.dao.ArchiveRecordDao;
import com.eascs.archive.entity.ArchiveExportEntity;
import com.eascs.archive.entity.ArchiveExportQueryVo;
import com.eascs.archive.entity.ArchiveLoanEntity;
import com.eascs.archive.entity.ArchiveRecordEntity;
import com.eascs.archive.entity.FieldEntity;
import com.eascs.archive.service.ArchiveExportService;
import com.eascs.archive.untils.ArchiveConstants;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;

@Service
public class ArchiveExportServiceImpl implements ArchiveExportService{
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ArchiveAdminDao archiveAdminDao;
	
	@Reference
	private SysOrgService SysOrgService;
	
	@Autowired
	private ArchiveRecordDao archiveRecordDao;
	
	@Autowired
	private  ArchiveServiceImpl archiveService;
	
	
	@Override
	public List<ArchiveExportQueryVo> buildArchiveExport(int pageSize, int pageIndex) {
		logger.info("定时任务计算归档数据,pageSize:[{}],pageIndex:[{}]", pageSize,pageIndex);
		if(pageIndex == 0){
			logger.info("开始删除历史数据");
			archiveAdminDao.deleteAllArchiveExport();
			logger.info("结束删除历史数据");
		}
		Calendar cl = Calendar.getInstance();  
		PageResult<ArchiveExportQueryVo> pageResult=archiveAdminDao.queryBuildExportByPage(pageSize, pageIndex);
		List<ArchiveExportQueryVo> data=pageResult.getData();
		for (ArchiveExportQueryVo vo : data) {
			try {
				String loanapplyNo=vo.getLoanapply_no();
				if(StringUtils.isBlank(vo.getBank_loan_name())){
					logger.info("贷款单放款银行为空,Loanapply_no:[{}]",loanapplyNo);
					continue;
				}
//				ArchiveExportEntity entity=archiveAdminDao.queryArchiveExport(loanapplyNo);
//				if (entity != null && StringUtils.equals(vo.getIs_place_on_file(), "CLO")) {
//					logger.info("定时任务计算归档导出数据---排除已经统计过的,Loanapply_no:[{}],ArchiveExportVo:[{}]",loanapplyNo,entity.toString());
//					continue;//排除已经统计过的
//				}else if (entity != null && !StringUtils.equals(vo.getIs_place_on_file(), "CLO")) {
//					logger.info("定时任务计算归档导出数据---未归档完成的重新统计，先删除后添加,Loanapply_no:[{}],ArchiveExportVo:[{}]",loanapplyNo,entity.toString());
//					archiveAdminDao.deleteArchiveExport(loanapplyNo);//未归档完成的重新统计
//				}
				
				ArchiveExportEntity exoprtVo=new ArchiveExportEntity(); 
				Class<?> cls = exoprtVo.getClass();
				
				String bankType=ArchiveConstants.getBankTypeId(vo.getBank_loan_name());
				BeanUtils.copyProperties(vo, exoprtVo);
				exoprtVo.setLoan_uname(vo.getUser_full_name());
				exoprtVo.setUser_idcard(vo.getDocument_no());
				exoprtVo.setEa_mount(vo.getLoan_amount());
				exoprtVo.setPayment_time(vo.getLoan_date());
				exoprtVo.setArchive_state(vo.getIs_place_on_file());
				cl.setTime(vo.getLoan_date());  
				cl.add(Calendar.MONTH, vo.getLoan_term());  
				exoprtVo.setTerm_time(cl.getTime());
				
				try {
					ActOrgEntity org= SysOrgService.getProvincialByOrgUnito(vo.getLtd());
					if(org != null)
						exoprtVo.setProvincial(org.getOrgName());
				} catch (Exception e) {
					logger.info("获取省区错误,参数vo:[{}],errorMsg:[{}],stack:[{}]",vo.toString(),e.getMessage(),e.getStackTrace());
				}
				List<ArchiveRecordEntity> archiveRecords=archiveRecordDao.queryArchiveRecordByLoanapplyNo(loanapplyNo);
				Map<String,ArchiveRecordEntity> map=new HashMap<>();
				for (ArchiveRecordEntity record : archiveRecords) {
					map.put(record.getFormTypeId(), record);
				}
				
				String wfNodeStatue="",sendFromId="";
				Date wfNodeTime=null;
				if(map.get(ArchiveConstants.FORMTYPE_BANK)!=null && map.get(ArchiveConstants.FORMTYPE_FINANCE)!=null
						&& map.get(ArchiveConstants.FORMTYPE_ARCHIVE_INFO)!=null){
					ArchiveRecordEntity bankArchive=archiveRecordDao.queryArchiveRecord(loanapplyNo, bankType, ArchiveConstants.FORMTYPE_BANK);
					ArchiveRecordEntity financeArchive=archiveRecordDao.queryArchiveRecord(loanapplyNo, bankType, ArchiveConstants.FORMTYPE_FINANCE);
					ArchiveRecordEntity cabinetArchive=archiveRecordDao.queryArchiveRecord(loanapplyNo, bankType, ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
					reflectSetField(bankArchive,exoprtVo,cls,bankType,ArchiveConstants.FORMTYPE_BANK);
					reflectSetField(financeArchive,exoprtVo,cls,bankType,ArchiveConstants.FORMTYPE_FINANCE);
					reflectSetField(cabinetArchive,exoprtVo,cls,bankType,ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
					
					sendFromId=ArchiveConstants.FORMTYPE_ARCHIVE_HQ_CHECK;
					wfNodeStatue="总部档案存柜确认";
					wfNodeTime= map.get(ArchiveConstants.FORMTYPE_BANK).getCreateTime();
				}else if(map.get(ArchiveConstants.FORMTYPE_ARCHIVE_HQ_CHECK)!=null){
					wfNodeStatue="总部档案管理审核";
					sendFromId=ArchiveConstants.FORMTYPE_ARCHIVE_PROVINCE_CHECK;
					wfNodeTime= map.get(ArchiveConstants.FORMTYPE_ARCHIVE_HQ_CHECK).getCreateTime();
				}else if(map.get(ArchiveConstants.FORMTYPE_ARCHIVE_PROVINCE_CHECK)!=null){
					wfNodeStatue="省区风控经理";
					sendFromId=ArchiveConstants.FORMTYPE_ARCHIVE;
					wfNodeTime= map.get(ArchiveConstants.FORMTYPE_ARCHIVE_PROVINCE_CHECK).getCreateTime();
				}else if(map.get(ArchiveConstants.FORMTYPE_ARCHIVE)!=null){
					wfNodeStatue="信贷经理";
					wfNodeTime= map.get(ArchiveConstants.FORMTYPE_ARCHIVE).getCreateTime();
				}
				if(StringUtils.isNoneBlank(sendFromId)){
					ArchiveRecordEntity sendArchive=archiveRecordDao.queryArchiveRecord(loanapplyNo, bankType, ArchiveConstants.FORMTYPE_ARCHIVE_HQ_CHECK);
					if(sendArchive != null){
						exoprtVo.setSend_company(sendArchive.getSendCompany());
						exoprtVo.setSend_no(sendArchive.getSendNo());
						exoprtVo.setSend_time(sendArchive.getSendTime());
					}
				}
				exoprtVo.setWf_node_state(wfNodeStatue);
				exoprtVo.setWf_node_time(wfNodeTime);
				
				archiveAdminDao.insertArchiveExport(exoprtVo);
			} catch (Exception e) {
				logger.info("定时任务计算归档数据错误,参数vo:[{}],errorMsg:[{}],stack:[{}]",vo.toString(),e.getMessage(),e.getStackTrace());
			}
		}
		
		return data;
	}
	
	
	public void reflectSetField(ArchiveRecordEntity recordvo,ArchiveExportEntity exoprtVo,Class<?> cls,String bankTypeId, String formTypeId){
		List<FieldEntity> bankFiled=archiveService.getFieldListByType(bankTypeId, formTypeId);
		try {
			String json = java.net.URLDecoder.decode(recordvo.getContentJson(), "UTF-8");
			JSONObject obj = JSONObject.parseObject(json);
			for (FieldEntity f : bankFiled) {
				String fieldValue = obj.getString(f.getFieldName());
				f.setFieldValue(fieldValue);
				try {
					if(formTypeId  == ArchiveConstants.FORMTYPE_ARCHIVE_INFO){//相同字段处理
						if(f.getFieldCode().equals("LOAN_CONTRACT"))
							exoprtVo.setCABINET_LOAN_CONTRACT( Integer.parseInt(fieldValue));
						else if(f.getFieldCode().equals("LOAN_NO"))
							exoprtVo.setCABINET_LOAN_NO( Integer.parseInt(fieldValue));
					}else{
						Method fieldSetMet = cls.getMethod("set" + f.getFieldCode(), Integer.class);
						fieldSetMet.invoke(exoprtVo, Integer.parseInt(fieldValue));  
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}


	@Override
	public PageResult<Object[]> queryListExport(ArchiveLoanEntity entity) {
		return archiveAdminDao.queryExportByPage(entity);
	}

}
